package help;

import burp.IExtensionHelpers;
import burp.IParameter;
import burp.IRequestInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by td on 2017/6/28.
 */
public class Myhelp  {

    private IExtensionHelpers helpers;

    private PrintWriter stdout;

    public Myhelp(IExtensionHelpers helpers,PrintWriter stdout) {
        this.helpers = helpers;
        this.stdout = stdout;
    }

    public Myhelp() {

    }

    public byte[] updateParameterJsonValue(byte[] request,IParameter iParameter,byte parametertype)throws Exception{
        if (parametertype!=IParameter.PARAM_JSON){
            throw new Exception("parameter type not is json");
        }

        IRequestInfo iRequestInfo = this.helpers.analyzeRequest(request);
        List<String> headers = iRequestInfo.getHeaders();

        String body="";

        String[] headersAndbody = this.helpers.bytesToString(request).split("\r\n\r\n",2);
        if (headersAndbody.length>0){
            body = headersAndbody[1];
        }

        JSONObject parameJsonobject = JSON.parseObject(body);

        Set<Map.Entry<String, Object>> parameSet =  parameJsonobject.entrySet();
        for (Map.Entry<String,Object> entry:parameSet){
            if (entry.getKey().equals(iParameter.getName())){
                entry.setValue(iParameter.getValue());
                break;
            }
        }
        byte[] updatedRequest = this.helpers.buildHttpMessage(headers,parameJsonobject.toJSONString().getBytes());

        return  updatedRequest;


    }

}
